// src/utils/request.js
import axios from "axios";
import { ElMessage } from "element-plus";
import { useUserStore } from "@/store/user";

// 创建axios实例
const service = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || "/api",
  timeout: 10000,
});

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    const userStore = useUserStore();

    // 添加token
    if (userStore.token) {
      config.headers["Authorization"] = `Bearer ${userStore.token}`;
    }

    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    const { data } = response;

    // 业务成功
    if (data.code === 0) {
      return data;
    }

    // 业务错误
    ElMessage.error(data.message || "请求失败");
    return Promise.reject(new Error(data.message || "请求失败"));
  },
  (error) => {
    // HTTP错误
    let message = "网络错误";

    if (error.response) {
      switch (error.response.status) {
        case 401:
          message = "未授权，请重新登录";
          useUserStore().logout();
          break;
        case 403:
          message = "拒绝访问";
          break;
        case 404:
          message = "请求地址不存在";
          break;
        case 500:
          message = "服务器内部错误";
          break;
        default:
          message = error.response.data?.message || "网络错误";
      }
    }

    ElMessage.error(message);
    return Promise.reject(error);
  }
);

export default service;
